<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="垃圾名称" prop="materialName">
        <el-input
          v-model="queryParams.materialName"
          placeholder="请输入垃圾名称"
          clearable
          @keyup.enter="handleQuery"
        />
        <!-- <el-select
          v-model="queryParams.materialName"
          placeholder="请选择垃圾名称"
          clearable
        >
          <el-option
            v-for="dict in sys_user_sex"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select> -->
      </el-form-item>
      <el-form-item label="垃圾类型" prop="materialType">
        <el-select
          v-model="queryParams.materialType"
          placeholder="请选择垃圾类型"
          clearable
        >
          <el-option
            v-for="dict in dict_trash_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="垃圾桶类型" prop="trashType">
        <el-select
          v-model="queryParams.trashType"
          placeholder="请选择垃圾桶类型"
          clearable
        >
          <el-option
            v-for="dict in trashTypeList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item label="点位名称" prop="pointName">
        <el-select
          v-model="queryParams.pointName"
          placeholder="请选择点位名称"
          clearable
        >
          <el-option
            v-for="dict in pointList"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:launch:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:launch:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:launch:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['system:launch:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="launchList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <!-- <el-table-column label="用户id" align="center" prop="userId" /> -->
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column label="垃圾id" align="center" prop="materialId" />
      <el-table-column label="垃圾名称" align="center" prop="materialName">
      </el-table-column>
      <el-table-column label="垃圾类型" align="center" prop="materialType">
      </el-table-column>
      <el-table-column label="垃圾桶id" align="center" prop="trashId" />
      <el-table-column label="垃圾桶类型" align="center" prop="trashType">
      </el-table-column>
      <el-table-column label="点位id" align="center" prop="pointId" />
      <el-table-column label="点位名称" align="center" prop="pointName">
      </el-table-column>
      <el-table-column label="投放日期" align="center" prop="launchDate" />
      <el-table-column label="投放时间" align="center" prop="launchTime" />
      <el-table-column label="容量" align="center" prop="capacity" />
      <el-table-column label="重量" align="center" prop="weight" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:launch:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:launch:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改投放收录对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="launchRef" :model="form" :rules="rules" label-width="80px">
        <!-- <el-form-item label="用户名称" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入用户名称" />
        </el-form-item> -->
        <el-form-item label="垃圾名称" prop="materialName">
          <el-select v-model="form.materialId" placeholder="请选择垃圾名称">
            <el-option
              v-for="dict in materialList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="垃圾类型" prop="materialType">
          <el-select v-model="form.materialType" placeholder="请选择垃圾类型">
            <el-option
              v-for="dict in dict_trash_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="点位名称" prop="pointName">
          <el-select v-model="form.pointId" placeholder="请选择点位名称">
            <el-option
              v-for="dict in pointList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="垃圾桶类型" prop="trashType">
          <el-select v-model="form.trashId" placeholder="请选择垃圾桶类型">
            <el-option
              v-for="dict in trashTypeList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="投放日期" prop="launchDate">
          <el-date-picker
            v-model="form.launchDate"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="投放时间" prop="launchTime">
          <el-time-picker
            v-model="form.launchTime"
            value-format="HH:mm:ss"
            format="HH:mm:ss"
            placeholder="选择时间"
          />
        </el-form-item>
        <el-form-item label="容量" prop="capacity">
          <el-input v-model="form.capacity" placeholder="请输入容量" />
        </el-form-item>
        <el-form-item label="重量" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Launch">
import { ElNotification } from 'element-plus'
import {
  listLaunch,
  getLaunch,
  delLaunch,
  addLaunch,
  updateLaunch,
} from "@/api/system/launch";
import { listPoint } from "@/api/system/point";
import { listMaterial } from "@/api/system/material";
import { listTrash } from "@/api/system/trash";
import { getCurrentInstance, ref, reactive, watch, onMounted } from "vue";
const { proxy } = getCurrentInstance();
const { sys_user_sex } = proxy.useDict("sys_user_sex");
const { dict_trash_type } = proxy.useDict("dict_trash_type");
const materialList = ref([]);
const trashTypeList = ref([]);
const pointList = ref([]);

const launchList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userName: null,
    materialName: null,
    materialType: null,
    trashType: null,
    pointName: null,
  },
  rules: {},
});

const { queryParams, form, rules } = toRefs(data);

/** 查询投放收录列表 */
function getList() {
  loading.value = true;
  listLaunch(queryParams.value).then((response) => {
    launchList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    // notify(); // 数据加载完成后立即执行检查
  });
}
function notify() {
  listLaunch({pageNum: 1, pageSize: 1000}).then((response) => {
    response.rows.forEach((item) => {
      console.log('trashType',item.trashType , item.materialType);
      
      if (item.trashType !== item.materialType) {
        ElNotification({
          title: "提示",
          message: `用户${item.userName}在点位名称为${item.pointName}的垃圾桶类型与垃圾类型不匹配`,
          type: "warning",
        });
      }
    });
  });
}

function getmaterialList() {
  listMaterial().then((response) => {
    // materialList.value = response.rows;
    materialList.value = response.rows.map((item) => ({
      value: item.id,
      label: item.materialName,
    }));
  });
}
// function getmateriaTypelList() {
//   loading.value = true;
//   listLaunch(queryParams.value).then((response) => {
//     materiaTypelList.value = response.rows;
//   });
// }
function getpointList() {
  listPoint().then((response) => {
    // pointList.value = response.rows;
    pointList.value = response.rows.map((item) => ({
      value: item.id,
      label: item.pointName,
    }));
  });
}
function gettrashTypeList(pointId) {
  listTrash({ pointId }).then((response) => {
    // trashTypeList.value = response.rows;
    trashTypeList.value = response.rows.map((item) => ({
      value: item.id,
      label: item.trashType,
    }));
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    userId: null,
    userName: null,
    materialId: null,
    materialName: null,
    materialType: null,
    trashId: null,
    trashType: null,
    pointId: null,
    pointName: null,
    launchDate: null,
    launchTime: null,
    capacity: null,
    weight: null,
    status: null,
    standby1: null,
    standby2: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null,
  };
  proxy.resetForm("launchRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加投放收录";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getLaunch(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改投放收录";
    //  await
  });
  gettrashTypeList(form.value.pointId);
}

/** 提交按钮 */
function submitForm() {
  materialList.value.forEach((item) => {
    if (item.value === form.value.materialId) {
      form.value.materialName = item.label;
    }
  });
  trashTypeList.value.forEach((item) => {
    if (item.value === form.value.trashId) {
      form.value.trashType = item.label;
    }
  });
  pointList.value.forEach((item) => {
    if (item.value === form.value.pointId) {
      form.value.pointName = item.label;
    }
  });
  proxy.$refs["launchRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateLaunch(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addLaunch(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
    .confirm('是否确认删除投放收录编号为"' + _ids + '"的数据项？')
    .then(function () {
      return delLaunch(_ids);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/launch/export",
    {
      ...queryParams.value,
    },
    `launch_${new Date().getTime()}.xlsx`
  );
}

getList();
getmaterialList();
getpointList();


// gettrashTypeList();
watch(
  () => form.value.pointId,
  (newVal) => {
    const selectedPoint = pointList.value.find((item) => item.value === newVal);
    if (selectedPoint) {
      gettrashTypeList(selectedPoint.value);
    }
  }
);
</script>
